import React, { useState, useEffect } from 'react';
import { HeaderDiv } from '../style'
import { getStorage, setStorage } from '@/utils/LocalStorage.js'
import {buyingMock} from '../../../model/loginModel'
import {
    Table, Input, DatePicker,
    Space, Button, InputNumber,
    Popconfirm, Form, Typography,
    Modal, Row, Col
} from 'antd';
import { SearchOutlined, PlusCircleOutlined } from '@ant-design/icons';
// 表格
const originData = [];
// 全自
const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

//
const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{
                        margin: 0,
                    }}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};
// mock上的表单
const layout = {
    labelCol: {
        span: 5,
    },
    wrapperCol: {
        span: 16,
    },
};


const Index = () => {
    
    // const originData = getStorage('lists')?JSON.parse(getStorage('lists')):[]
    //全选
    const [checkStrictly, setCheckStrictly] = React.useState(false);
    // 表格
    const [form] = Form.useForm();
    const [form1] = Form.useForm();

    const [data, setData] = useState([]);
    // const [valData , setValData] = useState({})
    let buylist = getStorage('lists')?JSON.parse(getStorage('lists')):[]
    const [editingKey, setEditingKey] = useState('');
    const [visible, setVisible] = useState(false);
   
    // mock上的表单

    const onFinish = (fieldsValue) => {
        const value = {
            ...fieldsValue,
            DatePicker:fieldsValue['date-picker'].format('YYYY-MM-DD')
        }
        buylist.push({
                    ...fieldsValue.user,
                    date:value.DatePicker,
                    key:Date.now()
                })
                setStorage('lists', JSON.stringify(buylist))
                    setVisible(false)
                    setData([...buylist])
        
    };
    async function setbuyingMock (){
        let res = await buyingMock()
        res = res.data.data
        let lists = [...res,...buylist]
        setData(lists)
    }
    const onFinishseave =( values) =>{
        console.log(values);
    }
  


 
    useEffect(() => {
        setData(buylist)
        setbuyingMock()
    }, []);
    const isEditing = (record) => record.key === editingKey;

    const edit = (record) => {
        form.setFieldsValue({
            name: '',
            age: '',
            address: '',
            ...record,
        });
        setEditingKey(record.key);
    };

    const cancel = () => {
        setEditingKey('');
    };
    // 表格操作
    const save = async (key) => {
        try {
            const row = await form.validateFields();
            const newData = [...data];
            const index = newData.findIndex((item) => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const columns = [
        {
            title: '发起日期',
            dataIndex: 'date',
            // width: '13%',
            editable: false,
            
        },
        {
            title: '请购单编号',
            dataIndex: 'numbering',
            // width: '13%',
            editable: true,
        },
        {
            title: '请购备注',
            dataIndex: 'buyState',
            // width: '10%',
            editable: true,
        },
        {
            title: '请购发起人',
            dataIndex: 'name',
            // width: '15%',
            editable: true,
        },
        {
            title: '请购负责人',
            dataIndex: 'functionary',
            // width: '15%',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <a
                            href="javascript:void(0);"
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            保存
            </a>
                        <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                            <a>取消</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        修改
                    </Typography.Link>
                );
            },
        },
        
          ];

    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    // modal框


    return (

        <HeaderDiv>

            {/* 头部 */}
            <div className='header'>
                <span>采购管理</span>
                <span>/</span>
                <strong>请购单管理</strong>
                <hr />
            </div>
            {/* input框 */}
            <div className='formBuying'>
                <div className='formone'>
                <Form
      form={form1}
      name="advanced_search"
      className="ant-advanced-search-form"
      onFinish={onFinishseave}
    >
          <Row gutter={24}>
            <Col span={8}   key={1}>
            <Form.Item
              name={`numbering`}
              label={`请购单编号 `}
              
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            <Col span={8}   key={2}>
            <Form.Item
              name={`name`}
              label={`请购发起人 `}
              
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            <Col span={8}   key={4}>
            <Form.Item
              name={`functionary`}
              label={`请购负责人 `}
              
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            </Row>
            
            {/* <Button className="buttonSearch"  icon={<SearchOutlined />} type="primary" htmlType="submit" size='large'>
            Search
          </Button> */}
          
        
         
                {/* 添加搜索按钮 */}
                <Form.Item>
                <div className="button">
                    <Button className="buttonSearch" type="primary" htmlType="submit"  icon={<SearchOutlined />} size='large'>
                        搜索
                    </Button>
                    <Button className="buttonAdd"  type="primary" onClick={() => setVisible(true)} icon={<PlusCircleOutlined />}>
                        添加
                     </Button>
            
                   
                </div>
                </Form.Item>
                </Form>
        </div>
                <hr />
            </div>
            <Form form={form} component={false}>

                <Table
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    dataSource={data}
                    columns={mergedColumns}
                    rowClassName="editable-row"
                    pagination={{
                        onChange: cancel,
                    }}
                    // columns={columns}
                    rowSelection={{ ...rowSelection, checkStrictly } }
                    dataSource={data}
                    
                />
                
            </Form>
            {/* modal框 */}
            <Modal
                title="添加请购单"
                centered
                visible={visible}
                footer={null}
                onCancel={() => setVisible(false)}
                width={700}
                
            >
                
                <Form {...layout} name="nest-messages" onFinish={onFinish} >
                <Form.Item
                        name='date-picker'
                        label="日期"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <DatePicker />
                    </Form.Item >
                    <Form.Item
                        name={['user', 'numbering']}
                        label="请购单编号"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name={['user', 'buyState']}
                        label="请购备注"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name={['user', 'functionary']}
                        label="请购发起人"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name={['user', 'name']}
                        label="请购负责人"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                   
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            添加
                        </Button>
                        <Button style={{ marginLeft: '20px' }} type="primary" onClick={() => setVisible(false)}>
                            取消
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>


        </HeaderDiv>
    );
}

export default Index;

